﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Web.UI.WebControls;

namespace Common
{
    public class Tools
    {
        /// <summary>
        /// 返回客户端真实IP地址
        /// </summary>
        public static string GetIpAddress()
        {
            string ip;
            if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) // 服务器， using proxy
            {
                //得到真实的客户端地址
                ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); // Return real client IP.
            }
            else//如果没有使用代理服务器或者得不到客户端的ip not using proxy or can't get the Client IP
            {

                //得到服务端的地址
                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
            }
            return ip;
        }

        public static void ShowInfo(string msg, string url, string target)
        {
            HttpContext ctx = HttpContext.Current;
            HttpSessionState session = ctx.Session;
            HttpRequest request = ctx.Request;
            HttpResponse response = ctx.Response;

            string contextRoot = request.Url.GetLeftPart(UriPartial.Authority);
            if (request.ApplicationPath != null && request.ApplicationPath != "/")
                contextRoot += request.ApplicationPath + "/";
            else
                contextRoot += "/";

            Hashtable ht = new Hashtable();
            ht["msg"] = msg;
            ht["url"] = url;
            ht["target"] = target;
            session["showInfo"] = ht;
            StringBuilder js = new StringBuilder();
            js.Append("<script type=\"text/javascript\">\n");
            js.Append("window.location.href='");
            js.Append(contextRoot + "Basic/Shared/ShowInfo.aspx?");
            js.Append(Guid.NewGuid().ToString());
            js.Append("';\n");
            js.Append("</script>\n");
            response.Write(js);
            response.End();
        }

        public static void Confirm(string msg, string okUrl, string okTarget, string cancelUrl, string cancelTarget)
        {
            HttpContext ctx = HttpContext.Current;
            HttpSessionState session = ctx.Session;
            HttpRequest request = ctx.Request;
            HttpResponse response = ctx.Response;

            string contextRoot = request.Url.GetLeftPart(UriPartial.Authority);
            if (request.ApplicationPath != null && request.ApplicationPath != "/")
                contextRoot += request.ApplicationPath + "/";
            else
                contextRoot += "/";

            Hashtable ht = new Hashtable();
            ht["msg"] = msg;
            ht["okUrl"] = okUrl;
            ht["okTarget"] = okTarget;
            ht["cancelUrl"] = cancelUrl;
            ht["cancelTarget"] = cancelTarget;
            session["confirm"] = ht;
            StringBuilder js = new StringBuilder();
            js.Append("<script type=\"text/javascript\">\n");
            js.Append("window.location.href='");
            js.Append(contextRoot + "Common/Confirm.aspx?");
            js.Append(new Guid().ToString());
            js.Append("';\n");
            js.Append("</script>\n");
            response.Write(js);
            response.End();
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="recordCount">总记录数</param>
        /// <param name="currentPage">当前页</param>
        /// <param name="pageUrl">基本URL地址</param>
        /// <returns>返回分页HTML</returns>
        public static string GetPageHtml(int pageSize, int recordCount, int currentPage, string pageUrl)
        {
            int pageCount;
            pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : recordCount / pageSize + 1;
            string str = string.Empty;
            StringBuilder sb = new StringBuilder();
            if (currentPage == 1)
            {
                sb.Append("<span class=\"noPage\">首页</span>  ");
                sb.Append("<span class=\"noPage\">上一页</span>  ");
            }
            else
            {
                sb.Append("<a href=\"" + pageUrl + "Page=1\" title=\"转至第1页\" class=\"a1\">首页</a> ");
                sb.AppendFormat("<a href=\"" + pageUrl + "Page={0}\" title=\"转至第{1}页\" class=\"a1\">上一页</a> ", currentPage - 1, currentPage - 1);
            }

            if (pageCount <= 9)
            {
                for (int i = 1; i <= pageCount; i++)
                {
                    if (i == currentPage)
                    {
                        sb.AppendFormat("<span class=\"currentPage\" data-key=\"1\">{0}</span> ", i);
                    }
                    else
                    {
                        sb.AppendFormat("<a href=\"" + pageUrl + "Page={0}\" title=\"转至第{1}页\">{1}</a> ", i, i);
                    }
                }
            }
            else
            {
                if (currentPage <= 5)
                {
                    for (int i = 1; i <= 9; i++)
                    {
                        if (i == currentPage)
                        {
                            sb.AppendFormat("<span class=\"currentPage\" data-key=\"1\">{0}</span> ", i);
                        }
                        else
                        {
                            sb.AppendFormat("<a href=\"" + pageUrl + "Page={0}\" title=\"转至第{1}页\">{1}</a> ", i, i);
                        }
                    }

                }
                else if (currentPage > (pageCount - 5))
                {
                    for (int i = 1; i <= 9; i++)
                    {
                        if ((pageCount - 9 + i) == currentPage)
                        {
                            sb.AppendFormat("<span class=\"currentPage\" data-key=\"1\">{0}</span> ", (pageCount - 9 + i));
                        }
                        else
                        {
                            sb.AppendFormat("<a href=\"" + pageUrl + "Page={0}\" title=\"转至第{1}页\">{1}</a> ", (pageCount - 9 + i), (pageCount - 9 + i));
                        }
                    }
                }
                else
                {
                    for (int i = 1; i <= 9; i++)
                    {
                        if ((currentPage - 5 + i) == currentPage)
                        {
                            sb.AppendFormat("<span class=\"currentPage\" data-key=\"1\">{0}</span> ", (currentPage - 5 + i));
                        }
                        else
                        {
                            sb.AppendFormat("<a href=\"" + pageUrl + "Page={0}\" title=\"转至第{1}页\">{1}</a> ", (currentPage - 5 + i), (currentPage - 5 + i));
                        }
                    }

                }
            }
            if (currentPage == pageCount)
            {
                sb.Append("<span class=\"noPage\">下一页</span>  ");
                sb.Append("<span class=\"noPage\">末页</span>   ");
            }
            else
            {
                sb.AppendFormat("<a href=\"" + pageUrl + "Page={0}\" title=\"转至第{1}页\" class=\"a1\">下一页</a>  ", currentPage + 1, currentPage + 1);
                sb.AppendFormat("<a href=\"" + pageUrl + "Page={0}\" title=\"转至第{1}页\" class=\"a1\">末页</a>  ", pageCount, pageCount);
            }
            return sb.ToString();
        }

        public static string MD5Encrypt(string str)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
        }

        public static string SymmetryEncrypt(string str)
        {
            SymmCrypto sc = new SymmCrypto(SymmCrypto.SymmProvEnum.DES);
            return sc.Encrypting(str, "yyy");
        }

        public static string SymmetryDecrypt(string str)
        {
            SymmCrypto sc = new SymmCrypto(SymmCrypto.SymmProvEnum.DES);
            return sc.Decrypting(str, "yyy");
        }

        public static bool IsAdminSessionValid()
        {
            bool flag = false;
            HttpContext.Current.Application.Lock();
            if (HttpContext.Current.Session["admin"] == null)
                flag = true;
            HttpContext.Current.Application.UnLock();
            return !flag;
        }

        public static object GetAdminSessionItem(string key)
        {
            object rtn = null;
            bool flag = false;
            HttpContext.Current.Application.Lock();
            if (HttpContext.Current.Session["admin"] == null)
                flag = true;
            else
                rtn = ((Hashtable)HttpContext.Current.Session["admin"])[key];
            HttpContext.Current.Application.UnLock();
            if (flag)
                throw new Exception(StringTable.SESSION_PROBLEM);
            else
                return rtn;
        }

        public static object[] GetAdminSessionItems(string keys)//key用逗号隔开
        {
            string[] a = keys.Split(',');
            object[] rtn = new object[a.Length];
            bool flag = false;
            HttpContext.Current.Application.Lock();
            if (HttpContext.Current.Session["admin"] == null)
                flag = true;
            else
            {
                for (int i = 0; i < a.Length; i++)
                    rtn[i] = ((Hashtable)HttpContext.Current.Session["admin"])[a[i]];
            }
            HttpContext.Current.Application.UnLock();
            if (flag)
                throw new Exception(StringTable.SESSION_PROBLEM);
            else
                return rtn;
        }

        public static void BubbleSort(IList<int> list)
        {
            int i, j, temp;
            bool done = false;
            j = 1;
            while ((j < list.Count) && (!done))
            {
                done = true;
                for (i = 0; i < list.Count - j; i++)
                {
                    if (list[i] > list[i + 1])
                    {
                        done = false;
                        temp = list[i];
                        list[i] = list[i + 1];
                        list[i + 1] = temp;
                    }
                }
                j++;

            }
        }

        public static string ToDateString(DateTime d)
        {
            return d.ToString("yyyy-MM-dd");
        }

        public static string ToDateTimeString(DateTime d)
        {
            return d.ToString("yyyy-MM-dd HH:mm:ss");
        }
        public static string GetPhysicalRootPath()
        {
            return HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath);
        }

        /// <summary>
        /// 去除一个数字数组中的所有重复数据
        /// </summary>
        /// <param name="intArray"></param>
        /// <returns></returns>
        public static int[] DeleteIntArrayRepeat(int[] intArray)
        {

            ArrayList arrInt = new ArrayList();
            Hashtable hshArray = new Hashtable();
            foreach (int p in intArray)
            {
                if (!hshArray.ContainsKey(p))
                {
                    hshArray.Add(p, p);
                    arrInt.Add(p);
                }
            }
            hshArray.Clear();
            hshArray = null;
            return (int[])arrInt.ToArray(typeof(int));
        }

        /// <summary>
        /// 去除一个字符串数组中的所有重复数据
        /// </summary>
        /// <param name="intArray"></param>
        /// <returns></returns>
        public static string[] DeleteStringArrayRepeat(string[] stringArray)
        {

            ArrayList arrInt = new ArrayList();
            Hashtable hshArray = new Hashtable();
            foreach (string p in stringArray)
            {
                if (!hshArray.ContainsKey(p))
                {
                    hshArray.Add(p, p);
                    arrInt.Add(p);
                }
            }
            hshArray.Clear();
            hshArray = null;
            return (string[])arrInt.ToArray(typeof(string));
        }

        /// <summary>
        /// 将一个字符串数组转化为用分割符隔开的连续字符串
        /// </summary>
        /// <param name="array">字符串数组</param>
        /// <param name="separator">分隔符，如"|"</param>
        /// <returns></returns>
        public static string StingArrayToString(string[] array, string separator)
        {
            StringBuilder _str=new StringBuilder();
            for (int i = 0; i < array.Length; i++)
            {
                if(i!=array.Length-1)
                    _str.Append(array[i] + separator);
                else
                    _str.Append(array[i]);
            }
            return _str.ToString();
        }

        /// <summary>
        /// 将一个数字数组转化为用分割符隔开的连续字符串
        /// </summary>
        /// <param name="array">数字数组</param>
        /// <param name="separator">分隔符，如"|"</param>
        /// <returns></returns>
        public static string IntArrayToString(int[] array, string separator)
        {
            StringBuilder _str = new StringBuilder();
            for (int i = 0; i < array.Length; i++)
            {
                if (i != array.Length - 1)
                    _str.Append(array[i].ToString() + separator);
                else
                    _str.Append(array[i].ToString());
            }
            return _str.ToString();
        }

        /// <summary>
        /// 将一个字符数组转化为数字数组,并自动去除其中的非数字元素
        /// </summary>
        /// <param name="array">字符数组</param>
        /// <returns></returns>
        public static int[] StringArrayToIntArray(string[] array)
        {
            ArrayList arrInt = new ArrayList();
            foreach (string p in array)
            {
                if(RegularExp.IsNumber(p))
                    arrInt.Add(int.Parse(p));
            }
            return (int[])arrInt.ToArray(typeof(int));
        }
    }
}
